package com.fingard.dsp.interact.custom.axatp;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.interact.DownloadFileReq;
import com.fingard.dsp.interact.DownloadFileResp;
import com.fingard.dsp.interact.FileServerInvokerBase;
import com.fingard.dsp.interact.GenerateUrlReq;
import com.fingard.dsp.interact.GenerateUrlResp;
import com.fingard.dsp.interact.IFileServerInvoker;
import com.fingard.dsp.interact.UploadFileReq;
import com.fingard.dsp.interact.UploadFileResp;
import com.fingard.generalobj.ExecResponse;
import com.fingard.io.FgFileHelper;
import com.fingard.text.StringHelper;

/**访问文件服务器调用类*/
public class FileServerInvoker extends FileServerInvokerBase implements IFileServerInvoker {
	
	private String logCode = "axatp"+File.separator+"FileServerInvoker";

	public void setLogCode(String pLogCode) {
		logCode = pLogCode;
	}
	
	public UploadFileResp uploadFile(UploadFileReq req){
		UploadFileResp resp = new UploadFileResp();
		resp.isCompleted = false;
		MultipartPostMethod method = null;
		try {
			String upfilename = StringHelper.getFileName(req.upFileLocalPath);
			String tmpfile = FgFileHelper.createTempFileDirectory("upfile")+File.separator+upfilename;
			File file = new File(tmpfile);
	            InputStream in= new FileInputStream(new File(req.upFileLocalPath));
	            method =  new MultipartPostMethod(fsSet.uploadUrl);

	            org.apache.commons.io.FileUtils.copyInputStreamToFile(in, file);

	            method.addParameter(tmpfile, tmpfile, file);
	            method.addParameter("systemName", fsSet.systemName);
	            method.addParameter("userName", fsSet.username);
	            HttpClient client = new HttpClient();
	            int statusCode = client.executeMethod(method);
	            //String responseBody = method.getResponseBodyAsString();// 获取返回信息
	            
	            InputStream inputStream = method.getResponseBodyAsStream();   
	            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));   
	            StringBuffer stringBuffer = new StringBuffer();   
	            String eachLine = "";   
	            while((eachLine = br.readLine()) != null){   
	                stringBuffer.append(eachLine);   
	            }
	            String responseBody = stringBuffer.toString();
	            inputStream.close();
	            br.close();
	            
	            if (statusCode != HttpStatus.SC_OK) {
	            	resp.appendMsgLn("响应内容："+responseBody);
					resp.appendMsgLn("请求状态："+statusCode);
	            } else {
	            	resp.isCompleted = true;
	            	
	            	resp.rtnFileId = parseXml(responseBody);
	                resp.appendMsgLn("上传成功，fileId："+resp.rtnFileId);
	            }

		}catch (HttpException e) {
				resp.sbMsg.append(e.getMessage()+"\r\n");
			} catch (IOException e) {
				resp.sbMsg.append(e.getMessage()+"\r\n");
			}finally {
				if (method != null) {
			        method.releaseConnection();
			      }
			}

		return resp;
	}
	
	
	 private static String parseXml(String result) {
		    Document doc;
		    String fileId = null;
		    try {
		      doc = DocumentHelper.parseText(result);
		      Element root = doc.getRootElement();
		      Iterator<Element> iter = root.elementIterator("attachment");
		      while (iter.hasNext()) {
		        Element attachment = (Element) iter.next();
		        fileId = attachment.elementTextTrim("fileid");
		      }
		    } catch (DocumentException e) {
		    	e.printStackTrace();
		    }
		    return fileId;
		  }
	
	public DownloadFileResp downloadFile(DownloadFileReq req){
		DownloadFileResp resp = new DownloadFileResp();
		
		PostMethod method = null;
		
		try{
			
			method = new PostMethod(fsSet.downloadUrl);
			//System.out.println("downloadUrl:"+fsSet.downloadUrl);
			method.addParameter("fileId", req.fileId);
			//System.out.println("fileId:"+req.fileId);
			method.addParameter("systemName", fsSet.systemName);
			//System.out.println("systemName:"+fsSet.systemName);
            method.addParameter("userName", fsSet.username);
            //System.out.println("userName:"+fsSet.username);
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int statusCode = client.executeMethod(method);
			
			if (statusCode != HttpStatus.SC_OK) {
				//String responseBody = method.getResponseBodyAsString();// 获取返回信息
				InputStream inputStream = method.getResponseBodyAsStream();   
	            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));   
	            StringBuffer stringBuffer = new StringBuffer();   
	            String eachLine = "";   
	            while((eachLine = br.readLine()) != null){   
	                stringBuffer.append(eachLine);   
	            }
	            String responseBody = stringBuffer.toString();
	            inputStream.close();
	            br.close();
	            resp.appendMsgLn(responseBody);
				//System.out.println("响应内容："+responseBody);
				//System.out.println("请求状态："+statusCode);
            } else {
            	resp.isCompleted = true;
            	//System.out.println("下载成功，fileId："+req.fileId);
            }
			
			resp.fileBytes = method.getResponseBody();
		}catch(Exception e){
			resp.sbMsg.append(e);
			e.printStackTrace();
		}finally{
			if(method!=null){
				method.releaseConnection();
			}
		}
		return resp;
	}
	
	public GenerateUrlResp generateUrl(GenerateUrlReq req) {
		GenerateUrlResp resp = new GenerateUrlResp();
		resp.isCompleted = false;
		resp.sbMsg.append("未实现该接口");
		return resp;
	}
	
	public ExecResponse pushData(ArrayList<ReceiptData> pDataList) {
		ExecResponse resp = new ExecResponse();
		resp.logMsg = "未实现该接口";
		return resp;
	}
}
